package com.shanghai.market.plshnaghai.utils;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectToFile {
	public static void writeObject(Object object, String fileName) {
		if (object == null || TextUtils.isEmpty(fileName))
			return;
		String filePath = getFilePath();
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		fileName = fileName + ".dat";
		File f = new File(file, fileName);
		try {
			ObjectOutputStream objectOutputStream = null;
			// RandomAccessFile ss = new RandomAccessFile(fileName, fileName);
			try {
				FileOutputStream outStream = new FileOutputStream(f);
				objectOutputStream = new ObjectOutputStream(outStream);
				objectOutputStream.writeObject(object);

			} finally {
				if (objectOutputStream != null)
					objectOutputStream.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressLint("SdCardPath")
	public static String getFilePath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}
		String filePath = sdDir.toString();
		if (filePath == null) {
			return "/data/data/";
		}
		filePath = filePath + "/Android/data/com.wondersgroup.fdsuperapp/cache/files";
		return filePath;
	}

	public static Object readObject(String fileName) {
		// ArrayList<MenuItem> list = new ArrayList<MenuItem>();
		if (TextUtils.isEmpty(fileName))
			return null;

		fileName = fileName + ".dat";
		ObjectInputStream objectInputStream = null;

		try {
			objectInputStream = new ObjectInputStream(new FileInputStream(getFilePath() + "/" + fileName));
			return objectInputStream.readObject();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (objectInputStream != null) {
					objectInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;

	}

	/**
	 * 根据文件名，删除一个文件
	 */
	public static void deleteExitsFile(String fileName) {
		try {
			String filePath = getFilePath();
			File file = new File(filePath, fileName + ".dat");
			if (file != null)
				file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
